package com.LeeCode;

/**
 * 删除链表的倒数第N个节点
 */
public class Code019 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        ListNode head = Utils.arrayToListNode(arr);

        new Code019().removeNthFromEnd(head, 1);
        Utils.printListNode(head);

    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode current = head, fast = head;

        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }
        if (fast == null) { // 要删除第一个节点
            return head.next;
        }
        while (fast.next != null) { // 要删除中间节点
            fast = fast.next;
            current = current.next;
        }
        current.next = current.next.next;
        return head;
    }

    public ListNode removeNthFromEnd1(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode fast = dummy, slow = dummy;
        for (int i = 0; i <= n; i++)
            fast = fast.next;
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }
}
